package com.jielin.handling.service.checkbody.impl;

import com.alibaba.fastjson.JSONObject;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.jielin.handling.entity.checkbody.TBody;
import com.jielin.handling.entity.checkbody.TBodyPic;
import com.jielin.handling.entity.tsuspect.TSuspec;
import com.jielin.handling.exception.ResultEnum;
import com.jielin.handling.mapper.checkbody.TBodyMapper;
import com.jielin.handling.mapper.checkbody.TBodyPicMapper;
import com.jielin.handling.mapper.tsuspect.TSuspecMapper;
import com.jielin.handling.service.checkbody.CheckBodyService;
import com.jielin.handling.service.xsky.XskyService;
import com.jielin.handling.util.ConstantUtil;
import com.jielin.handling.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * Created by wangjienice on 2019/3/18.
 */
@Service
@Slf4j
public class CheckBodyServiceImpl implements CheckBodyService {
    @Autowired
    TBodyMapper tBodyMapper;
    @Autowired
    TBodyPicMapper tBodyPicMapper;
    @Autowired
    TSuspecMapper tSuspecMapper;
    @Autowired
    private XskyService xskyService;


    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int insert(TBody tBody) {
        log.info("tBody:{}", JSONObject.toJSONString(tBody));
        try {
            String id = StringUtil.generatorUUID();
            tBody.setId(id);
            TSuspec tSuspec = new TSuspec();
            tSuspec.setId(tBody.getSuspectId());
            TSuspec suspectState = tSuspecMapper.selectStatue(tBody.getSuspectId());
            if (!"8".equals(suspectState.getSuspectState())) {
                tSuspec.setSuspectState("2");
            } else {
                tSuspec.setSuspectState(suspectState.getSuspectState());
            }
            tSuspecMapper.updateState(tSuspec);
            return tBodyMapper.insert(tBody);
        } catch (Exception e) {
            log.info("service 事务回滚:{}", e);
            //抛出异常让其回滚
            throw new RuntimeException("事务回滚");
        }
    }

    @Override
    public void delectCheckBody(String suspectId) {
        tBodyMapper.delectCheckBody(suspectId);
    }

    @Override
    public int saveWoundPhoto(TBodyPic tBodyPic) {
        log.info("tBodyPic:{}", JSONObject.toJSONString(tBodyPic));
        return tBodyPicMapper.insert(tBodyPic);
    }

    @Override
    public int updateWoundPhoto(String id) {
        log.info("id:{}", JSONObject.toJSONString(id));

        return tBodyPicMapper.updateWoundPhoto(id);
    }

    @Override
    public List<TBodyPic> selectAllPic(String suspectId) {
        log.info("id:{}", JSONObject.toJSONString(suspectId));
        List<TBodyPic> list = tBodyPicMapper.selectAllPic(suspectId);
        for (TBodyPic tBodyPic : list) {
            if (!ConstantUtil.XSKYRESTORAGE) {
                String returnPath = ConstantUtil.SERVER_URL + tBodyPic.getPicUrl();
                tBodyPic.setPicUrl(returnPath);
            }

        }
        return list;
    }

    @Override
    public List<TBodyPic> selectById(String suspectId) {

        return tBodyPicMapper.selectById(suspectId);
    }

    @Override
    public int updateWound(TBodyPic tBodyPic) {
        return tBodyPicMapper.updateWound(tBodyPic);
    }

    @Override
    public TBodyPic saveWoundPhoto2(MultipartFile file, String suspectId, String fileString) {
        TBodyPic tBodyPic = new TBodyPic();
        log.info("tBodyPic:{}", JSONObject.toJSONString(tBodyPic));
        boolean b = file != null && file.getSize() > 0;
        if (b || !StringUtil.isEmpty(fileString)) {
            String path = ConstantUtil.PHOTO_PATH + "suspect" + File.separatorChar + "wound" + File.separatorChar;
            String trueFileName = String.valueOf(System.currentTimeMillis());
            byte[] bytes = null;
            //设置Metadata
            ObjectMetadata metadata = new ObjectMetadata();
            if (b) {
                try {
                    String fileName = file.getOriginalFilename();
                    String fileType = fileName.substring(fileName.lastIndexOf("."));
                    String filesPath = path + trueFileName + fileType;
                    tBodyPic.setId(StringUtil.generatorUUID());
                    tBodyPic.setPicUrl(ConstantUtil.XSKY_PHOTO_URL + filesPath);
                    tBodyPic.setSuspectId(suspectId);
                    filesPath = filesPath.replace("\\", "/");
                    bytes = file.getBytes();
                    metadata.setContentType(file.getContentType());
                    xskyService.uploadObjectForInputStream(ConstantUtil.XSKY_BUCKET_PHOTO, filesPath, bytes, metadata);
                } catch (IOException e) {
                    e.printStackTrace();
                    log.error("xsky上传失败");
                    return null;
                }
            } else {
                try {
                    String fileType = ".png";
                    String filesPath = path + trueFileName + fileType;
                    tBodyPic.setId(StringUtil.generatorUUID());
                    tBodyPic.setPicUrl(ConstantUtil.XSKY_PHOTO_URL + filesPath);
                    tBodyPic.setSuspectId(suspectId);
                    filesPath = filesPath.replace("\\", "/");
                    BASE64Decoder decoder = new BASE64Decoder();
                    String base64String = fileString.substring(fileString.indexOf(",") + 1);// 去掉头部（不能解析）
                    log.info("Base64解码后:\n" + base64String);
//                    byte[] b = new byte[0];
                    bytes = decoder.decodeBuffer(base64String);
                    for (int i = 0; i < bytes.length; ++i) {
                        if (bytes[i] < 0) {// 调整异常数据
                            bytes[i] += 256;
                        }
                    }
                    try {
                        metadata.setContentType(ContentType.IMAGE_JPEG.getMimeType());
                        xskyService.uploadObjectForInputStream(ConstantUtil.XSKY_BUCKET_PHOTO, filesPath, bytes, metadata);
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error("xsky上传失败！");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }
            }

            if (tBodyPicMapper.insert(tBodyPic) > 0) {
                log.info("上传成功");
                return tBodyPic;
            } else {
                log.error("上传失败");
            }
        }
        return null;

    }

}
